//
//  ViewController.swift
//  加法计算器
//
//  Created by 侯国兵 on 2017/4/21.
//  Copyright © 2017年 BJZK. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    var firstValue: UITextField?
    var secondValue: UITextField?
    var sumValue: UILabel?
    
    override func viewDidLoad() {
        super.viewDidLoad()
         setupUI()
    }
    

    func sum()  {
        guard let num1 = Int(firstValue?.text ?? ""),
          let num2 = Int(secondValue?.text ?? "") else {
            print("必须都输入数字才能计算")
            return
        }
        sumValue?.text = "\(num1 + num2)"
       
        
        
    }
    func clear(){
        firstValue?.text = "0"
        secondValue?.text = "0"
        sumValue?.text = "0"
    }
    
    func setupUI() -> () {
        //第一个参数
        let value1 = UITextField(frame: CGRect(x: 20, y: 60, width: 100,height: 30))
        value1.borderStyle = .roundedRect
        value1.text = "0"
        value1.keyboardType = .numberPad
        view.addSubview(value1)
        firstValue = value1
        
        //第二个参数
        let value2 = UITextField(frame: CGRect(x: 140, y: 60, width: 100,height: 30))
        value2.borderStyle = .roundedRect
        value2.text = "0"
        value2.keyboardType = .numberPad
        view.addSubview(value2)
        secondValue = value2
        
        //加号
        let lab1 = UILabel(frame: CGRect(x: 120, y: 60, width: 20, height: 30))
        lab1.text = "+"
        lab1.textAlignment = .center
        view.addSubview(lab1)
        
        //等号
        let lab2 = UILabel(frame: CGRect(x: 240, y: 60, width: 20, height: 30))
        lab2.text = "="
        lab2.textAlignment = .center
        view.addSubview(lab2)
        
        //和
        let lab3 = UILabel(frame: CGRect(x: 260, y: 60, width: 100, height: 30))
        lab3.text = "0"
        lab3.textAlignment = .left
        view.addSubview(lab3)
        sumValue = lab3
        
        //求和
        let sumBtn = UIButton(frame: CGRect(x:100, y:160, width: 60, height: 30))
        sumBtn.setTitle("求和", for: UIControlState.normal)
        sumBtn.setTitleColor(UIColor.blue, for: UIControlState.normal)
        sumBtn.backgroundColor = UIColor.brown
        sumBtn.sizeToFit()
        sumBtn.addTarget(self, action: #selector(sum), for: .touchUpInside)
        view.addSubview(sumBtn)
        
        
        //清零
        let clearBtn = UIButton(frame: CGRect(x:200, y:160, width: 60, height: 30))
        clearBtn.setTitle("清零", for: UIControlState.normal)
        clearBtn.setTitleColor(UIColor.blue, for: UIControlState.normal)
        clearBtn.backgroundColor = UIColor.brown
        clearBtn.sizeToFit()
        clearBtn.addTarget(self, action: #selector(clear), for: .touchUpInside)
        view.addSubview(clearBtn)
    }
 


}

